package com.heima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
/**
 * 阿里云 OSS 工具类
 */
@Component
public class AliOSSUtils {

    @Autowired
            private AliOssObject aliOssObject;
    //@Value("${aliyun.oss.endpoint}")
   // String endpoint = aliOssObject.getEndpoint();
    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    // 填写Bucket名称，例如examplebucket。
    //@Value("${aliyun.oss.accessKeyId}")
    //String accessKeyId =aliOssObject.getAccessKeyId();
    //@Value("${aliyun.oss.accessKeySecret}")
    //String accessKeySecret = aliOssObject.getAccessKeySecret();
    //@Value("${aliyun.oss.bucketName}")
   // String bucketName = aliOssObject.getBucketName();
    // 填写Object完整路径，完整路径中不能包含Bucket名称，

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {


        String endpoint = aliOssObject.getEndpoint();
        String accessKeyId =aliOssObject.getAccessKeyId();
        String accessKeySecret = aliOssObject.getAccessKeySecret();
        String bucketName = aliOssObject.getBucketName();
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}
